package com.lemon.smartsafetynew.ui.fragment.contact;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafetynew.ui.fragment.base.ToolbarBaseFragment;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.contact.PersonVo;
import com.lemon.smartsafetynew.net.services.ContactServices;
import com.lemon.smartsafetynew.ui.activity.contact.ContactDetailActivity;
import com.lemon.smartsafetynew.ui.adapter.contact.SortAdapter;
import com.lemon.smartsafetynew.ui.widget.SideBarView;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.contact.PinyinComparator;
import com.lemon.smartsafetynew.util.contact.PinyinUtils;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;

/**
 * Created by Andrew on 2017/9/18.
 */

public class ContactFragment extends ToolbarBaseFragment
        implements RecyclerTClickListener<PersonVo> {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.dialog)
    TextView dialog;
    @Bind(R.id.sideBar)
    SideBarView sideBar;

    private User user;

    private SortAdapter adapter;

    private LinearLayoutManager manager;

    private List<PersonVo> SourceDateList = new ArrayList<>();

    /**
     * 根据拼音来排列RecyclerView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @Override
    protected int getTitle() {
        return R.string.draw_contact;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_contact_home;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initData();

        pinyinComparator = new PinyinComparator();

        sideBar.setTextView(dialog);

        //设置右侧SideBar触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBarView.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String str) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(str.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position, 0);
                }

            }
        });

        manager = new LinearLayoutManager(getmContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new SortAdapter(getmContext(), SourceDateList, this);
        recyclerView.setAdapter(adapter);

        getContactList();
    }

    /**
     * 为RecyclerView填充数据
     *
     * @param list
     * @return
     */
    private List<PersonVo> filledData(List<PersonVo> list) {
        List<PersonVo> mSortList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            PersonVo personVo = list.get(i);
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(list.get(i).getUser_name());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                personVo.setLetters(sortString.toUpperCase());
            } else {
                personVo.setLetters("#");
            }

            mSortList.add(personVo);
        }
        return mSortList;

    }

    /**
     * 获取所有联系人
     */
    private void getContactList() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("company_id", user.getCompanyId());
        params.put("department_id", user.getGovId());

        ContactServices
                .init()
                .getAllUser(params);
    }

    @Override
    public void onItemClick(PersonVo data, int position) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_PERSON, data);
        UIHelper.showActivity(getmContext(), bundle, ContactDetailActivity.class);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GET_ALL_PERSON.equals(event.getTag())) {

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
                mHUDUtil.show();
            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    List<PersonVo> personVos = (List<PersonVo>) event.getObj();
                    SourceDateList.clear();
                    SourceDateList = filledData(personVos);
                    Collections.sort(SourceDateList, pinyinComparator);
                    adapter.updateList(SourceDateList);

                } else if (Constants.Result.ERROR == event.getEventResult()) {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        }
    }

    /**
     * 初始化数据变量
     */
    private void initData() {

        user = AccountUtil.getUser();

        if (user == null) {
            mHUDUtil.showErrorTip("用户信息为空，请重新登陆！", new HUDUtil.CallBack() {
                @Override
                public void onCall() {

                }
            });
        }
    }

}
